import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

// 负责数据库的创建和升级
class DatabaseHelper {
  // 单例模式
  static final DatabaseHelper _instance = DatabaseHelper._internal();
  DatabaseHelper._internal();

  static Database? _database;
  static const _dbName = 'flutter_again.db';
  static const _dbVersion = 1;

  static DatabaseHelper get instance => _instance;

  // 获取数据库实例
  Future<Database> get database async {
    _database ??= await _initDatabase();
    return _database!;
  }

  Future<Database> _initDatabase() async {
    final path = join(await getDatabasesPath(), _dbName);
    return await openDatabase(path, version: _dbVersion, onCreate: _onCreate);
  }

  Future _onCreate(Database db, int version) async {
    await db.execute('''
      CREATE TABLE website_links (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        title TEXT NOT NULL,
        description TEXT,
        url TEXT NOT NULL,
        create_time TEXT NOT NULL DEFAULT current_timestamp
      )
    ''');
    // 可以在这里创建更多表
  }

  // 在应用生命周期结束时关闭数据库（可选，但推荐）
  Future close() async {
    final db = _database;
    if (db != null) {
      await db.close();
    }
  }
}
